<?php
/**
 * 运行时日志清理
 */
namespace app\shell;

use share\console\CConsole;
use share\console\CLIRunner;
use share\utils\Helper;

class CRuntimeLog  extends CLIRunner{

    /**
     * 默认保留最后10天的日志
     */
    public function auto_remove_action($days = 10){    
        $endTime = strtotime("- ".$days." days");
        $endMonth = date("Ym",$endTime);
        $endDay = date("Ymd",$endTime);
        $basePath = realpath(RUNTIME_PATH);
        $data = scandir($basePath);
        foreach($data as $path){
            if($path == '.' || $path == '..' ){
                continue;
            }
            if(self::isCurlLog($path)){
                $filenameInfo = explode(".",$path);
                if(count($filenameInfo) == 3){
                    if($filenameInfo[1] <= $endDay){
                  
                        CConsole::print_line("remove file ".$path);

                        unlink($basePath.DIRECTORY_SEPARATOR.$path);
                    }
                }
            }
            else if($path == "log"){
                $logPath = $basePath.DIRECTORY_SEPARATOR.$path;
                $logPathFiles = scandir($logPath);
                foreach($logPathFiles as $logFile){
                    if($logFile == '.' || $logFile == '..' ){
                        continue;
                    }
                    if($logFile < $endMonth){
              
                        CConsole::print_line("remove dir ".$logPath.DIRECTORY_SEPARATOR.$logFile);

                        Helper::rmdir($logPath.DIRECTORY_SEPARATOR.$logFile);
                    }
                    else if($logFile == $endMonth){
                        $logMonthPath = $logPath.DIRECTORY_SEPARATOR.$logFile;
                        $logMonthLogPath = scandir($logMonthPath);
                        foreach($logMonthLogPath as $log){
                            $tmpFile = $logMonthPath.DIRECTORY_SEPARATOR.$log;
                            if(is_file($tmpFile)){
                                $filetime = filectime($tmpFile);
                                // CConsole::print_line($tmpFile." filectime is ".date("YmdHis",$filetime));
                                if($filetime && $filetime < $endTime){                        
                                    CConsole::print_line("remove file ".$tmpFile);

                                    unlink($tmpFile);
                                }
                            }
                        }

                    }
                }
            }
        }

        return $data;
    }


    public static function isCurlLog($path){
        return preg_match("/^curl_access\.\d{8}\.log$/",$path);
    }

  
}